package com.itheima.sh.controller;

import com.itheima.sh.pojo.User;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
public class ConsumerController {

    @Autowired
    private RestTemplate restTemplate;

//    @Autowired
//    private DiscoveryClient discoveryClient;

    @GetMapping("{id}")
    @HystrixCommand(fallbackMethod = "FindUserFallBack")
    public User queryById(@PathVariable("id") String username) {
//        String url = "http://localhost:8083/user/" + username;

        //解决方案1：discoverClient
//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
//        ServiceInstance instance = instances.get(0);
//        String host = instance.getHost();
//        int port = instance.getPort();
////        String uri = instance.getUri().toString();
////        String url = "http://"+uri+"/user/" + username;
//        String url = "http://"+host+":"+port+"/user/" + username;
        // 调用RestTemplate的getForObject方法，指定url地址和返回值类型
        String url = "http://user-service/user/"+username;
        User user = restTemplate.getForObject(url, User.class);
        return user;
    }


    // 备选方案
    public User FindUserFallBack(String username) {
        User user = new User();
        user.setEmail("-1");
        user.setUsername(username);
        user.setName("暂停服务");
        return user;
    }
}
